package com.guojiang.guopicturebackend.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guojiang.guopicturebackend.annotation.AuthCheck;
import com.guojiang.guopicturebackend.common.BaseResponse;
import com.guojiang.guopicturebackend.common.DeleteRequest;
import com.guojiang.guopicturebackend.common.ResultUtils;
import com.guojiang.guopicturebackend.constant.UserConstant;
import com.guojiang.guopicturebackend.exception.ErrorCode;
import com.guojiang.guopicturebackend.exception.ThrowUtils;
import com.guojiang.guopicturebackend.model.dto.user.*;
import com.guojiang.guopicturebackend.model.entity.User;
import com.guojiang.guopicturebackend.model.vo.picture.PictureTagCategoryVO;
import com.guojiang.guopicturebackend.model.vo.user.LoginMaskedUserVO;
import com.guojiang.guopicturebackend.model.vo.user.MaskedUserVO;
import com.guojiang.guopicturebackend.model.vo.user.UserRoleVO;
import com.guojiang.guopicturebackend.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR, "userRegisterRequest 为空");
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        long newUserId = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(newUserId);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<LoginMaskedUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR, "userLoginRequest 为空");
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        LoginMaskedUserVO loginMaskedUserVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(loginMaskedUserVO);
    }

    /**
     * 获取脱敏当前登录用户信息
     *
     * @param request
     * @return 脱敏后的当前登录用户信息
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginMaskedUserVO> getLoginMaskedUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        LoginMaskedUserVO loginMaskedUserVO = userService.getLoginMaskedUserVO(loginUser);
        return ResultUtils.success(loginMaskedUserVO);
    }

    /**
     * 用户登出
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        boolean logoutResult = userService.userLogout(request);
        return ResultUtils.success(logoutResult);
    }

    /**
     * 创建用户（管理员使用）
     *
     * @param userAddRequest
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR, "userAddRequest 为空");
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        // 设置默认密码
        final String DEFAULT_PASSWORD = "12345678";
        String encryptPassword = userService.getEncryptPassword(DEFAULT_PASSWORD);
        user.setUserPassword(encryptPassword);
        boolean saveResult = userService.save(user);
        ThrowUtils.throwIf(!saveResult, ErrorCode.OPERATION_ERROR, "创建用户失败");
        return ResultUtils.success(user.getId());
    }

    /**
     * 根据 id 获取用户（管理员使用）
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取脱敏用户
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<MaskedUserVO> getMaskedUserVOById(long id) {
        // 复用 getUserById
        BaseResponse<User> response = this.getUserById(id);
        User user = response.getData();
        return ResultUtils.success(userService.getMaskedUserVO(user));
    }

    /**
     * 删除用户（管理员使用）
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() <= 0, ErrorCode.PARAMS_ERROR, "deleteRequest 为空");
        boolean removeResult = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(removeResult);
    }

    /**
     * 更新用户（管理员使用）
     *
     * @param userUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        ThrowUtils.throwIf(userUpdateRequest == null, ErrorCode.PARAMS_ERROR, "userUpdateRequest 为空");
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean updateResult = userService.updateById(user);
        ThrowUtils.throwIf(!updateResult, ErrorCode.OPERATION_ERROR, "更新用户失败");
        return ResultUtils.success(true);
    }

    /**
     * 分页展示脱敏用户列表（管理员使用）
     *
     * @param userQueryRequest
     * @return
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<MaskedUserVO>> listMaskedUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR, "userQueryRequest 为空");
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, pageSize)
                , userService.getQueryWrapper(userQueryRequest));
        // 新建脱敏用户分页，大小（getTotal）与 userPage 一样 
        // current表示从第几页开始，pageSize表示一页有多少条数据，getTotal表示总共多少条数据
        Page<MaskedUserVO> maskedUserVOPage = new Page<>(current, pageSize, userPage.getTotal());
        // 获取脱敏用户列表
        List<MaskedUserVO> maskedUserVOList = userService.getMaskedUserVOList(userPage.getRecords());
        // 将脱敏用户列表放入脱敏用户分页
        maskedUserVOPage.setRecords(maskedUserVOList);
        return ResultUtils.success(maskedUserVOPage);
    }

    /**
     * 获取常见的图片标签、分类列表（主页展示）
     *
     * @return
     */
    @GetMapping("/role")
    public BaseResponse<UserRoleVO> listUserRole() {
        UserRoleVO userRoleVO = new UserRoleVO();
        List<String> userRoleList = Arrays.asList("user","admin","vip","svip");
        userRoleVO.setUserRoleList(userRoleList);
        return ResultUtils.success(userRoleVO);
    }
}
